package com.jiuyuan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiuyuan.entity.Admin;
import com.jiuyuan.entity.Role;
import com.jiuyuan.entity.vo.RespBean;
import com.jiuyuan.entity.vo.RespBeanEnum;
import com.jiuyuan.mapper.AdminMapper;
import com.jiuyuan.mapper.RoleMapper;
import com.jiuyuan.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuyuan.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiuyuan
 * @since 2023-02-15
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;


    @Override
    public Admin getAdminByUsername(String name) {

        return adminMapper.selectOne(
                new QueryWrapper<Admin>()
                        .eq("enabled",true)
                        .eq("username",name)

        );
    }

    @Override
    public List<Role> getRolesByAdminId(Integer id) {
        return roleMapper.getRolesByAdminId(id);
    }

    @Override
    public RespBean allList(String keyBoard) {
        List<Admin> admins = adminMapper.allList(AdminUtils.getCurrentAdmin().getId(),keyBoard);
        return RespBean.success(admins);
    }

    @Override
    public RespBean updatePass(Integer adminId, String oldPass, String pass) {
        Admin admin = adminMapper.selectById(adminId);
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        int result = -1;
        if (passwordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(passwordEncoder.encode(pass));
            result = adminMapper.updateById(admin);

        }
        if (result==-1) return RespBean.error(RespBeanEnum.UPDATE_FILED);
        return RespBean.success(RespBeanEnum.SUCCESS);
    }
}
